package com.base.listNode;

public class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode();
        dummy.next = new ListNode(0);
        ListNode node = dummy;
        while (l1 != null && l2 != null) {
            int jinwei = (l1.val + l2.val + node.next.val) / 10;
            int total = (l1.val + l2.val + node.next.val) % 10;

            node.next.val = total;
            node.next.next = new ListNode(jinwei);

            l1 = l1.next;
            l2 = l2.next;
            node = node.next;
        }
        while (l2 != null) {
            if (node.next.val == 0) {
                node.next = l2;
                break;
            }
            int jinwei = (l2.val + node.next.val) / 10;
            int total = (l2.val + node.next.val) % 10;
            node.next.val = total;
            node.next.next = new ListNode(jinwei);
            l2 = l2.next;
            node = node.next;
        }

        while (l1 != null) {
            if (node.next.val == 0) {
                node.next = l1;
                break;
            }
            int jinwei = (l1.val + node.next.val) / 10;
            int total = (l1.val + node.next.val) % 10;
            node.next.val = total;
            node.next.next = new ListNode(jinwei);
            l1 = l1.next;
            node = node.next;
        }

        if (node.next.val < 1 && node.next.next == null) {
            node.next = null;
        }

        return dummy.next;
    }

    public ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode();
        ListNode cur = dummy;
        //进位
        int carry = 0;

        while (l1 != null || l2 != null || carry != 0) {
            //将进位也进行加法
            int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
            carry = s / 10;
            cur.next = new ListNode(s % 10);
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
            cur = cur.next;
        }
        return dummy.next;


    }
}
